package midas.mw.crt.security;


import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.*;

import midas.mw.cfg.CfgError;
import midas.mw.cfg.CfgLogging;
import midas.mw.cfg.log.Logger;
import midas.mw.crt.CrtException;


/**
 * This class allows to authenticate a user in private WiFi network
 */
public class Authenticator 
{
	/**
	 * URL to provide authentication
	 */
	private String httpsURL = null;
	
	/**
	 * Network operator
	 */
	private String operator = null;
	
	/**
	 * Username
	 */
	private String username = null;
	
	/**
	 * Password
	 */
	private String password = null;
	
	/**
	 * Constructor - initiate local variables
	 *
	 * @param httpsURL URL to provide authentication
	 * @param operator Network operator
	 * @param username Username
	 * @param password Password
	 */
	public Authenticator(String httpsURL, String operator, String username, String password)
	{
		CfgLogging.logEvent(CfgLogging.LOG_MCALL, Logger.COMPONENT_CRT, CfgLogging.SEV_DEBUG, "Authenticator(" +
				httpsURL + ", " + operator + ", " + username + ", " + password + ")");
		
		this.httpsURL = httpsURL;
		this.operator = operator;
		this.username = username;
		this.password = password;
	}
	
	/**
	 * Sends the authentication parameters to the specified URL
	 * @throws CrtException If the authentication fails
	 */
	public void sendAuthentication() throws CrtException
	{
		CfgLogging.logEvent(CfgLogging.LOG_MCALL, Logger.COMPONENT_CRT, CfgLogging.SEV_DEBUG, "Authenticator.sendAuthentication()");
		
		try{
			
			URL myurl = new URL(httpsURL);
			String postParameters= encodeParameter("operator", operator)+ "&" + encodeParameter("username", username) +"&" + encodeParameter("password", password);
			HttpURLConnection con = (HttpURLConnection) myurl.openConnection();
		    con.setDoOutput(true);
		    OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
		    osw.write(postParameters);
		    osw.flush();
		    
		    //HTTPS Response Code
		    if (con.getResponseCode() != HttpURLConnection.HTTP_OK &&
                    con.getResponseCode() != 100) {            	
                throw new IOException("HTTP Error: " +
                        con.getResponseCode() + " " +
                        con.getResponseMessage());
            }
		    
		} catch (IOException ioe) {
			CfgError.errorReporting(CfgError.ERR_OPER, "Authenticator.sendAuthentication()", CfgError.SEV_FATAL, 
					"Authenticator.sendAuthentication(). Error io: " + ioe.getMessage(), null);
            //System.out.println("Error polling: " + t.getMessage());
        	ioe.printStackTrace();
            throw new CrtException();
		}
	}
	
	/**
	 * Translates a pair name-value strings into application/x-www-form-urlencoded format using a UTF-8 encoding scheme
	 * @param name Name to be encoded
	 * @param value Value to be encoded
	 * @return The translated string
	 * @throws UnsupportedEncodingException If the named encoding is not supported
	 */
	String encodeParameter(String name, String value) throws UnsupportedEncodingException 
	{
		CfgLogging.logEvent(CfgLogging.LOG_MCALL, Logger.COMPONENT_CRT, CfgLogging.SEV_DEBUG, "Authenticator.encodeParameter(" + name + ", " + value + ")");
		
		return URLEncoder.encode(name,"UTF-8")+ "=" + URLEncoder.encode(value,"UTF-8"); 
	}
}
